package com.star.sync.elasticsearch.config;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Map;

/**
 * @author <a href="mailto:wangchao.star@gmail.com">wangchao</a>
 * @version 1.0
 * @since 2017-08-25 17:26:00
 */
@Component
public class CanalConfig implements DisposableBean {
    private static final Logger logger = LoggerFactory.getLogger(CanalConfig.class);
    private CanalConnector canalConnector;

    @Value("${canal.cluster.nodes}")
    private String canalClusterNodes;
    @Value("${canal.destination}")
    private String canalDestination;
    @Value("${canal.username}")
    private String canalUsername;
    @Value("${canal.password}")
    private String canalPassword;

    @Bean("canalConnector")
    public CanalConnector getCanalConnector() {

        Map<String, String> nodes = Splitter.on(',')
                .trimResults()
                .omitEmptyStrings()
                .withKeyValueSeparator(':')
                .split(canalClusterNodes);
        if (nodes.isEmpty()) {
            throw new IllegalArgumentException("clusterNodes格式不正确！要求ip1:port1,ip2:port2");
        }
        ArrayList addressList =new ArrayList();
        for (Map.Entry<String, String> entry : nodes.entrySet()) {
            String canalHost = entry.getKey();
            int canalPort = Integer.parseInt(entry.getValue());
            addressList.add(new InetSocketAddress(canalHost, Integer.valueOf(canalPort)));
        }

        canalConnector = CanalConnectors.newClusterConnector(addressList, canalDestination, canalUsername, canalPassword);
        canalConnector.connect();
        // 指定filter，格式 {database}.{table}，这里不做过滤，过滤操作留给用户
        canalConnector.subscribe();
        // 回滚寻找上次中断的位置
        canalConnector.rollback();
        logger.info("canal客户端启动成功");
        return canalConnector;
    }

    @Override
    public void destroy() throws Exception {
        if (canalConnector != null) {
            canalConnector.disconnect();
        }
    }
}
